const http = require('../../utils/http.js');
const app = getApp();
var regeneratorRuntime = require("../../utils/regenerator-runtime/runtime-module.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hide_good_box: true,
    typeId: 0,
    tabShow: false,
    imgUrls: ['http://img3.imgtn.bdimg.com/it/u=107380887,308295474&fm=26&gp=0.jpg',
      'http://img3.imgtn.bdimg.com/it/u=107380887,308295474&fm=26&gp=0.jpg',
      'http://img3.imgtn.bdimg.com/it/u=107380887,308295474&fm=26&gp=0.jpg'
    ],

    navArr: [],
    navArr1: [],
    goodsArr: [],
    shopCarNum: 0, //购物车商品数量
    scrollLeft: 0,
  },
  //获取轮播图
  getBnaner() {
    var sid = wx.getStorageSync('nowSchool').id
    http.fetchApi('procedure_t', { p: 'R2007010|' + sid + '|2' }).then(res => {
      if (res.data.code == 1) {
        var imgUrls = res.data.results;
        this.setData({
          imgUrls
        })
      }
    })
  },
  //轮播图链接商详情
  toShopDetail(e) {
    var good_id = e.currentTarget.dataset.id;
    console.log(good_id)
    wx.navigateTo({
      url: '../goodsDetail/goodsDetail?gid=' + good_id,
    })
  },
  //精选推荐
  jingxuan() {
    this.setData({
      tabShow: true
    })
  },

  //获取商品列表
  async getGoodsList(page, goodsTypeId, search = "%%") {
   
    return new Promise((resoved,reject)=>{
     // var sid = wx.getStorageSync('nowSchool').id;
      var sid = wx.getStorageSync('nowAddress').school_id;
      var uid = app.globalData.uid;

      var params = {
        p: 'R1001006',
        k: page,
        j: 20,
        cs: sid + '|' + goodsTypeId + '|' + search + '|' + uid
      }

      http.fetchApi('procedureList', params).then(res => {
        if (res.data.code == 1) {
         
          if (page == 1) {
            this.setData({
              goodsArr: []
            })
          }
          var goodsArr = this.data.goodsArr;
          var goodsArr1 = res.data.results;
          if (goodsArr1.length == 0 && page > 1) {
            // http.showToast('再拉也没有啦!' + '', '', 'none')
            return
          }
          goodsArr = [...goodsArr, ...goodsArr1]
          this.setData({
            goodsArr,
            page
          })
          
          resoved(goodsArr)
          // wx.pageScrollTo({
          //   scrollTop: this.data.scrollTop || 0,
          //   duration: 0
          // })
        }
      })
    })
   
  },

  //获取商品类型

  async getGoodsType() {
    // var school_id = wx.getStorageSync('nowSchool').id;
    var school_id = wx.getStorageSync('nowAddress').school_id;
    http.fetchApi('procedure_t', {
      p: 'R2002007|' + school_id
    }).then(res => {
      
      if (res.data.code == 1) {

        var navArr = res.data.results;
        var navArr1 = [...navArr];
        if (navArr.length == []) {
          wx.showModal({
            title: '提示',
            content: '您选的校区暂无商品',
          })

        }
        navArr1.unshift({
          lx_name: '全部',
          id: 0
        })
        
        this.setData({
          navArr,
          navArr1
        })
      }
    })
  },

  //切换商品类型
  changeType(e) {
    var typeId = e.currentTarget.id;
    var goodsID = e.currentTarget.dataset.goodsid;
   
    this.setData({
      typeId,
      goodsID
    })
    if (typeId >= 4) {
      this.setData({
        scrollLeft: 100 * (typeId - 4 + 1),
      })
    } else {
      this.setData({
        scrollLeft: 0
      })
    }

    this.setData({
      goodsArr: []
    })
    this.getGoodsList(1, goodsID);
  },

  //商品选择大类
  goodsType(e) {
    var goodsID = e.currentTarget.dataset.goodsid;
    this.setData({
      tabShow: true
    })
    var typeId = e.currentTarget.id
    this.setData({
      typeId
    })

    if (typeId >= 4) {
      this.setData({
        scrollLeft: 100 * (typeId - 4 + 1),
      })
    } else {
      this.setData({
        scrollLeft: 0
      })
    }

   
    this.setData({
      goodsArr: []
    })
    this.getGoodsList(1, goodsID);
  },
  //input聚焦跳转search页面
  toSearch() {

    wx.navigateTo({
      url: '../search/search',
    })
  },

  //跳转购物车
  toShopCar(e) {
    var formId = e.detail.formId;
    console.log(formId)
    var uid = app.globalData.uid;
    wx.request({
      url: app.globalData.host + 'procedure_t',
      method: 'post',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: { p: 'R2013001|' + formId + '|' + uid },
      complete: () => {
        wx.navigateTo({
          url: '../shopCarDetail1/shopCarDetail1',
        })
      }
    })

  
  },

  //本地缓存取商品
  getGoodsNum() {
    var shopCar = wx.getStorageSync('shopCar1') || [];
    var num = 0;
    shopCar.forEach((item, index) => {
      num += item.goods_sl
    })
    this.setData({
      shopCarNum: num
    })
  },


  //加入购物车
  addNum(e) {
    //将添加的商品存入本地缓存
    var shopCar = wx.getStorageSync('shopCar1') || [];
    
    var item = e.currentTarget.dataset.item;
    // if (!item.goods_sl) { item.goods_sl = 1}
    item.goods_sl = 1;
    item.is_select = false;


    if (shopCar.length == 0) {

      shopCar.push(item);
    } else {
      var findSameId = shopCar.findIndex((i, d) => item.shid == i.shid);
      if (findSameId == -1) {
        wx.showModal({
          content: '你所购买的商品商家不统一，请将当前购物车商品进行结算后，再继续购物。',
          success: (res) => {
            if (res.confirm) {
              this.toShopCar();
            } else if (res.cancel) {

            }
          }
        })

        return
      } else{
        var shopCar1 = shopCar.filter((item2, index) => {
          return item2.gid == item.gid
        })
        if (shopCar1.length == 0) {
          shopCar.push(item);
        } else {
          shopCar.forEach((item1, index) => {
            if (item1.gid == item.gid) {
              item1.goods_sl++;
            }
          })
        }
      }
     
    }



    wx.setStorageSync('shopCar1', shopCar);

    this.getGoodsNum();
    //飞入购物车效果
    this.touchOnGoods(e);

  },

  touchOnGoods: function(e) {
    // 如果good_box正在运动
    if (!this.data.hide_good_box) return;
    this.finger = {};
    var topPoint = {};
    this.finger['x'] = e.touches["0"].clientX;
    this.finger['y'] = e.touches["0"].clientY;
    if (this.finger['y'] < this.busPos['y']) {
      topPoint['y'] = this.finger['y'] - 150;
    } else {
      topPoint['y'] = this.busPos['y'] - 150;
    }
    topPoint['x'] = Math.abs(this.finger['x'] - this.busPos['x']) / 2;
    if (this.finger['x'] > this.busPos['x']) {
      topPoint['x'] = (this.finger['x'] - this.busPos['x']) / 2 + this.busPos['x'];
    } else {
      topPoint['x'] = (this.busPos['x'] - this.finger['x']) / 2 + this.finger['x'];
    }
    this.linePos = app.bezier([this.finger, topPoint, this.busPos], 20);
    this.startAnimation();
  },
  startAnimation: function() {
    var index = 0,
      that = this,
      bezier_points = that.linePos['bezier_points'],
      len = bezier_points.length - 1;
    this.setData({
      hide_good_box: false,
      bus_x: that.finger['x'],
      bus_y: that.finger['y']
    })
    this.timer = setInterval(function() {
      index++;
      that.setData({
        bus_x: bezier_points[index]['x'],
        bus_y: bezier_points[index]['y']
      })
      if (index >= len) {
        clearInterval(that.timer);
        that.setData({
          hide_good_box: true,
        })
      }
    }, 15);
  },

  //跳转商品详情
  toGoodsDetail(e) {
    var gid = e.currentTarget.dataset.gid
    wx.navigateTo({
      url: '../goodsDetail/goodsDetail?gid=' + gid,
    })
  },
  //监听页面滚动
  onPageScroll: function (e) {
    
    this.setData({
      scrollTop: e.scrollTop
    })

    if (e.scrollTop > this.data.windowHeight / 5) {

      this.setData({
        tabShow: true
      })


    }
  },

  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    
    wx.getSystemInfo({
      success: (res) => {
        this.setData({
          windowHeight: res.windowHeight
        })
      }
    })

    this.busPos = {};
    this.busPos['x'] = 20;
    this.busPos['y'] = app.globalData.hh;

    console.log('购物车坐标', this.busPos, app.globalData.hh);

    this.getGoodsList(1, 0);

  },

 
  

  

  /**
   * 生命周期函数--监听页面初次渲染完成
   */

  onReady: function() {




  },

  
  /**
   * 生命周期函数--监听页面显示
   */

  onShow: function() {
    this.getBnaner()
    this.getGoodsType();
    if (app.globalData.isAddCheckSchool == 1) {
      this.getGoodsList(1, 0);
      app.globalData.isAddCheckSchool = 0
    }
    this.getGoodsNum();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */

  onHide: function() {


  },

  /**
   * 生命周期函数--监听页面卸载
   */

  onUnload: function() {


  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */

  onPullDownRefresh: function() {


  },

  /**
   * 页面上拉触底事件的处理函数
   */

  onReachBottom: function() {
    var page = this.data.page || 1;
    page++;
    this.getGoodsList(page, this.data.goodsID || 0);


  },
  onPullDownRefresh: function() {
   
    this.setData({
      tabShow: false
    })
    wx.stopPullDownRefresh();
  },
  /**
   * 用户点击右上角分享
   */

  onShareAppMessage: function() {

  }
})